<?php
/*
  The only really fancy thing this page has is the slider.  Other than that, it's pretty static.
*/
?>

<?php
  if (!isset($_COOKIE['ys-parcelNum'])) {
    setcookie('noParcelNum',true);
    $u = explode('/',$_SERVER['REQUEST_URI']);
    array_pop($u);
    $u = 'http://'.$_SERVER['SERVER_NAME'].implode('/',$u).'/?page=introLocation';
    header('Location: '.$u);
  }
  else if (!isset($_COOKIE['ys-stormwaterShort'])) {
    setcookie('noStormwater',true);
    $u = explode('/',$_SERVER['REQUEST_URI']);
    array_pop($u);
    $u = 'http://'.$_SERVER['SERVER_NAME'].implode('/',$u).'/?page=introStormwater';
    header('Location: '.$u);
  }
  $isRegistered = isset($_SESSION['gdusername']) AND isset($_SESSION['gdpassword']);

  $alertNoPollution = false;
  if (isset($_COOKIE['noPollution'])) {
    $alertNoPollution = true;
    setcookie('noPollution','',time() - 3600);
  }

  $thumbnail = 'img/blank.png';
  if (isset($_COOKIE['ys-parcelThumbnail'])) {
    $thumbnail = substr($_COOKIE['ys-parcelThumbnail'],2);
  }
?>
  <body onload="Ext.onReady(function(){init()})">
    <script>
      var stormwaterFull;
      var stormwaterShort;
      var pollution = <?php echo substr($_COOKIE['ys-parcelRegulated'],2) == 'True' ? 65 : 10?>;

      var performanceStore;
      var stormwaterControlConstraintStore;
      var stormwaterStore;
      var parcelInfoStore;
      var pollutionNumberField;
      var pollutionSlider;
      var cp;

      function init() {
        // IE9 having problems w/ slider.  Naturally.
        Ext.override(Ext.dd.DragTracker, {
            onMouseMove: function (e, target) {
                var isIE9 = Ext.isIE && (/msie 9/.test(navigator.userAgent.toLowerCase())) && document.documentMode != 6;
                if (this.active && Ext.isIE && !isIE9 && !e.browserEvent.button) {
                    e.preventDefault();
                    this.onMouseUp(e);
                    return;
                }
                e.preventDefault();
                var xy = e.getXY(), s = this.startXY;
                this.lastXY = xy;
                if (!this.active) {
                    if (Math.abs(s[0] - xy[0]) > this.tolerance || Math.abs(s[1] - xy[1]) > this.tolerance) {
                        this.triggerStart(e);
                    } else {
                        return;
                    }
                }
                this.fireEvent('mousemove', this, e);
                this.onDrag(e);
                this.fireEvent('drag', this, e);
            }
        });

        document.getElementById('pollutionSlider').style.visibility = 'visible';
        document.getElementById('pollutionNumberField').style.visibility = 'visible';
        document.getElementById('pollutionPercent').style.visibility = 'visible';
        document.getElementById('pollutionLabels').style.visibility = 'visible';

        Ext.get('loading').fadeOut({duration : 0.2,remove : true});
        Ext.QuickTips.init();

        cp = new Ext.state.CookieProvider({
          expires : new Date(new Date().getTime()+(1000*60*60*24*30)) //30 days
        });
        Ext.state.Manager.setProvider(cp);

        stormwaterFull  = cp.get('stormwaterFull');
        stormwaterShort = cp.get('stormwaterShort');
        pollution       = cp.get('pollution') ? cp.get('pollution') : pollution;
        cp.set('pollution',pollution);

        performanceStore                 = initPerformanceStore();
        stormwaterControlConstraintStore = initBmpConstraintStore();
        stormwaterStore                  = initBmpTypeStore();

        // create a fake parcelInfoStore based on cookies
        parcelInfoStore = new Ext.data.ArrayStore({
          fields : [
             'Regulated'
            ,'Owner Name'
            ,'Dep2HWT (in)'
            ,'Dep2ResLyr (in)'
            ,'Hyd Soil Group'
            ,'KSat (in/hr)'
            ,'Imperv Area (ac)'
            ,'UpLand Area (ac)'
            ,'Wetland Area (ac)'
            ,'Total Area (ac)'
            ,'Perv Load (lb/yr)'
            ,'Imperv Load'
            ,'Total Load (lb/yr)'
            ,'Slope (%)'
            ,'Load Credit/Deficit (lb/yr)'
          ]
          ,data : [[
             cp.get('parcelRegulated')
            ,cp.get('parcelOwner Name')
            ,cp.get('parcelDep2HWT (in)')
            ,cp.get('parcelDep2ResLyr (in)')
            ,cp.get('parcelHyd Soil Group')
            ,cp.get('parcelKSat (in/hr)')
            ,cp.get('parcelImperv Area (ac)')
            ,cp.get('parcelUpLand Area (ac)')
            ,cp.get('parcelWetland Area (ac)')
            ,cp.get('parcelTotal Area (ac)')
            ,cp.get('parcelPerv Load (lb/yr)')
            ,cp.get('parcelImperv Load')
            ,cp.get('parcelTotal Load (lb/yr)')
            ,cp.get('parcelSlope (%)')
            ,cp.get('parcelLoad Credit/Deficit (lb/yr)')
          ]]
        });

        // This is the little text field where a user can enter a value and/or see the slider's value.
        pollutionNumberField = new Ext.form.NumberField({
           renderTo  : 'pollutionNumberField'
          ,width     : 40
          ,minValue  : 1
          ,maxValue  : 100
          ,value     : pollution
          ,listeners : {
            specialkey : function(field,e) {
              if (e.getKey() == e.ENTER) {
                field.fireEvent('change',field,field.getValue());
              }
            }
            ,change    : function(field,newVal,oldVal) {
              cp.set('pollution',newVal);
              pollutionSlider.suspendEvents();
              pollutionSlider.setValue(newVal);
              pollutionSlider.resumeEvents();
              computeCost();
            }
          }
        });

        // Fancy slider.
        pollutionSlider = new Ext.Slider({
           width     : 400
          ,minValue  : 1
          ,maxValue  : 100
          ,value     : pollution
          ,plugins   : new Ext.slider.Tip({
            getText : function(thumb) {return String.format('{0}%',thumb.value)}
          })
          ,renderTo  : 'pollutionSlider'
          ,listeners : {
            afterrender : function(slider) {
              slider.addListener('change',function(slider,newVal,oldVal) {
                cp.set('pollution',newVal);
                pollutionNumberField.suspendEvents();
                pollutionNumberField.setValue(newVal);
                pollutionNumberField.resumeEvents();
                computeCost();
              });
              Ext.defer(function(){computeCost()},100);
            }
          }
        });

<?php
  if ($alertNoPollution) {
?>
        Ext.Msg.alert('No pollution reduction amount selected',"You were brought back to this page because you need to select a pollution reduction amount before continuing.");
<?php
  }
?>
      }

      function computeCost() {
        // And away we go . . .
        cp.clear('totalCost');
        var wqd         = calcWQD(stormwaterShort,pollutionSlider.getValue() / 100,performanceStore);
        var loadRemoved = calcLoadRemoved(stormwaterShort,wqd,parcelInfoStore,performanceStore);
        var costFactor  = getBmpConstraintCostFactor('Partly developed area',stormwaterControlConstraintStore);
        var unitCost    = getBmpTypeUnitCost(stormwaterFull,stormwaterStore);
        var wqVolume    = calcWQVolume(parcelInfoStore,wqd);
        var totalCost   = costFactor * unitCost * wqVolume;
        unitCost        = totalCost / loadRemoved;

        cp.set('wqd',Math.round(wqd * 10000) / 10000);
        cp.set('totalCost','$' + CommaFormatted(new String(Math.round(totalCost))));
        cp.set('unitCost','$' + CommaFormatted(new String(Math.round(unitCost))));
        cp.set('loadRemoved',Math.round(loadRemoved * 100) / 100);
        var loadCreditDeficit = ((pollutionSlider.getValue() / 100 - (parcelInfoStore.getAt(0).get('Regulated') == 'True' ? 0.65 : 0.10)) * parcelInfoStore.getAt(0).get('Total Load (lb/yr)')).toFixed(2);
        if (parcelInfoStore.getAt(0).get('Regulated') != 'True' && loadCreditDeficit < 0) {
          loadCreditDeficit = Number(0).toFixed(2);
        }
        cp.set('loadCreditDeficit',loadCreditDeficit);
        if (loadCreditDeficit < 0) {
          document.getElementById('pollutionLabel').innerHTML = 'Deficit';
          document.getElementById('pollutionValue').innerHTML = '<font color="red">' + loadCreditDeficit + '</font>';
        }
        else if (parcelInfoStore.getAt(0).get('Regulated') != 'True' && loadCreditDeficit == 0) {
          document.getElementById('pollutionLabel').innerHTML = 'Credit';
          document.getElementById('pollutionValue').innerHTML = '<font color="#b8860b"> +' + loadCreditDeficit + '</font>';
        }
        else {
          document.getElementById('pollutionLabel').innerHTML = 'Credit';
          document.getElementById('pollutionValue').innerHTML = '<font color="green"> +' + loadCreditDeficit + '</font>';
        }
        document.getElementById('designCost').innerHTML = '$' + CommaFormatted(new String(Math.round(totalCost)));
        var recommendation = [];
        if (parcelInfoStore.getAt(0).get('Regulated') == 'True') {
          if (new RegExp(/^(C|D|C\/D|U)$/).test(parcelInfoStore.getAt(0).get('Hyd Soil Group'))) {
            recommendation.push('<font color="red">Soils on this parcel may be very low quality for filtering stormwater. Consider buying credits in order to meet permit requirements.</font>');
          }
          else if (pollutionSlider.getValue() == 65) {
            recommendation.push('<font color="green">You are meeting permit requirements for pollution reduction.</font>');
          }
          else if (pollutionSlider.getValue() > 65) {
            recommendation.push('<font color="green">Great, you are exceeding permit requirements for pollution reduction! Your design may earn credits.</font>');
          }
          else {
            recommendation.push('<font color="red">Regulated sites are required to achieve a 65% reduction. Increase the reduction percent, or consider trading to meet the permit requirement.</font>');
          }
        }
        else {
          if (new RegExp(/^(C|D|C\/D|U)$/).test(parcelInfoStore.getAt(0).get('Hyd Soil Group'))) {
            recommendation.push('<font color="red">Soils on this parcel may be very low quality for filtering stormwater. Pollution reduction may not be possible for this unregulated site.</font>');
          }
          else if (pollutionSlider.getValue() > 10) {
            recommendation.push('<font color="green">Great, your unregulated site will earn credits for any reduction made!</font>');
          }
          else {
            recommendation.push('<font color="green">Your unregulated site will earn credits for any reduction made over 10%.</font>');
          }
        }
        document.getElementById('notice').innerHTML = recommendation.join('<br>');
      }
    </script>

    <style>
      #pollutionDiv {
        width    : 500px;
        height   : 76px;
        position : relative;
      }
      #pollutionSlider {
        position : absolute;
        top      : 0px;
        left     : 10px;
        visibility : hidden;
      }
      #pollutionSlider .x-slider-thumb {
        background-image:url(images/slider-thumb.png);
      }
      #pollutionNumberField {
        position : absolute;
        top      : 0px;
        right    : 20px;
        visibility : hidden;
      }
      #pollutionPercent {
        position : absolute;
        top      : 0px;
        right    : 0px;
        visibility : hidden;
      }
      #pollutionLabels {
        position : absolute;
        top      : 25px;
        left     : 0px;
        width    : 425px;
        visibility : hidden;
      }
      #pollutionLabels td {
        font-weight : bold;
      }
    </style>

    <div id="site">
<?php include_once('header.php')?>
        <div id="content">
            <div class="home-screen clearfix">

                <div class="left-column" style="width: 500px;">
                    <h2 style="margin-bottom: 20px;">Pollution Reduction</h2>
<?php
  if (substr($_COOKIE['ys-parcelRegulated'],2) == 'True') {
?>
               			<p>You can now determine how efficient to design the stormwater control. Please enter the percentage of pollution reduction you wish to achieve. Regulated sites are required to achieve at least a 65% pollution reduction.</p>
               			<ul style="list-style: disc;">
               				<li>Reductions greater than 65% will earn credits that may be traded.</li>
               				<li>Reductions under 65% will require purchase of credits to meet permit  requirements.</li>
               			</ul>
<?php
  }
  else {
?>
                                <p>You can now determine how efficient to design the stormwater control. Please enter the percentage of pollution reduction you wish to achieve. Unregulated sites are not required to achieve any pollution reduction, but Exchange will reward credits for any reduction over 10%.</p>
                                <ul style="list-style: disc;">
                                        <li>Reductions are completely optional for unregulated sites.</li>
                                        <li>Reductions greater than 10% will earn credits that may be traded.</li>
                                </ul>
<?php
  }
?>
               			<p>Once you have adjusted the pollution reduction, Exchange will adjust the design cost.</p>
               			<p style="font-style: italic;">Drag the slider to adjust pollution reduction or enter reduction percent in the designated box.</p>
               			<div id="pollutionDiv">
                                  <div id="loading"><span id="loading-message">Loading. Please wait...</span></div>
                                  <div id="pollutionSlider"></div>
                                  <div id="pollutionNumberField"></div>
                                  <div id="pollutionPercent">%</div>
                                  <div id="pollutionLabels"><table><tr>
<?php
  if (substr($_COOKIE['ys-parcelRegulated'],2) == 'True') {
?>
                                    <td style="width:238px">0%</td>
                                    <td style="width:60px;text-align:center">65%<br>Required</td>
                                    <td style="width:127px;text-align:right">100%</td>
<?php
  }
  else {
?>
                                    <td style="width:24px">0%</td>
                                    <td style="width:60px;text-align:center">10%<br>Minimum<br>for credit<br>accural</td>
                                    <td style="width:341px;text-align:right">100%</td>
<?php
  }
?>
                                  </tr></table></div>
                                </div>
               		</div>
               		<div class="right-column">
                          <table id="blue-box">
                            <tr><th><div id="step-four" class="progress-bar">&nbsp;</div></th></tr>
                            <tr><td>
                              <div id="small_map"><img src="<?php echo $thumbnail?>"></div>
<?php
  if ($isRegistered) {
?>
                              <p><label class="item first">Property Owner:</label><label><?php echo substr($_COOKIE['ys-parcelOwner_Name'],2)?></label></p>
<?php
}
else {
?>
                              <p><label class="item first">Property Address:</label><label><?php echo substr($_COOKIE['ys-parcelPhys_Addr1'],2).', '.substr($_COOKIE['ys-parcelPhys_City'],2)?></label></p>
<?php
}
?>
                              <p>
                                <label class="item">Area (Acres)</label><br>
                                <label class="item">Total:</label><label><?php echo sprintf("%.2f",substr($_COOKIE['ys-parcelTotal_Area_(ac)'],2))?></label><br>
                                <label class="item">Impervious:</label><label><?php echo sprintf("%.2f",substr($_COOKIE['ys-parcelImperv_Area_(ac)'],2))?></label>
                              </p>
                              <p><label class="item">Stormwater Control:</label><label><?php echo substr($_COOKIE['ys-stormwaterFull'],2)?></label></p>
                              <p><label class="item">Pollution <span id="pollutionLabel"></span>:</label><label id="pollutionValue"></label></p>
                              <p><label class="item">Design Cost:</label><label id="designCost"></label></p>
                              <p class="notice" id="notice"></p>
                            </td></tr>
                          </table>
                    <p style="text-align: center; margin-top: 10px; margin-left: 30px; width: 240px;"><a class="info" id="changing pollution reduction" href="#">How does changing pollution reduction effect design costs?</a></p>
               		</div>
               		<div style="padding-top: 20px; clear: both;">
               			<p>Click Next to continue to the next step.</p>
               			<a href="?page=introStormwater"><img src="images/back_but.png" style="vertical-align: top; margin-top: 10px;" alt="Back" title="Back" /></a>
										<a href="?page=introResults"><img src="images/next_but.png" style="vertical-align: top; margin-left: 570px; margin-top: 10px;" alt="Next" title="Next" /></a>						</div>

            </div>
        </div>
<?php include_once('footer.php')?>
    </div>
    <script type="text/javascript" src="./js/ext-3.4.0/adapter/ext/ext-base.js"></script>
    <script type="text/javascript" src="./js/ext-3.4.0/ext-all.js"></script>
    <script type="text/javascript" src="./js/calcs.js"></script>
    <script type="text/javascript">
      $(document).ready(function(){
        var clickHereLinks = initClickHereLinks('introPollution');
        infoWindow = $('table#info-window');
        $('a.info').click(function(e){
          e.preventDefault();
          $('table#info-window tr:eq(1) td:first').html(clickHereLinks[$(this).attr('id')]);
          infoWindow.show()
        });
        $('table#info-window tr td a').click(function(e){
          e.preventDefault();
          infoWindow.hide();
        });
        $('body').live('keydown', function (e) {
            if (infoWindow.css('display') != 'none'){
                var charCode = e.charCode || e.keyCode;
                if (charCode == 27)
                    infoWindow.css('display', 'none');
            }
        });
      });
    </script>
    <table id="info-window">
      <tr><td style="margin:0;padding:4px 7px 0 0;text-align:right;font-size: 16px;font-weight:bold;"><a href="" style="text-decoration:none;">X</a></td></tr>
      <tr><td style="padding-top:0;"></td></tr>
      <tr><td style="text-align: center; padding: 0;"><a href="">close</a></td></tr>
    </table>
  </body>
